using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class XuHuang : MonoBehaviour
{
    // 将军基本属性
    public string generalName = "徐晃";
    public int health = 200;
    // 是否正在战斗
    public bool is_attacking = false;
    // 是否到达目的地
    public bool is_arrive = false;
    // 所属国家
    public string country = "Wei";
    // 士兵数量
    public int archerAccount;    // 弓箭手数量
    public int infantryAccount;  // 步兵数量
    public int cavalryAccount;  // 骑兵数量

    // 当前所在区域坐标
    public string currentPosition;
    // 目标区域坐标
    public string targetPosition;
    // 阵型
    public string formation;

    // 活动
    public string activity;

    [Header("移动设置")]
    public float speed = 2f;                    // 移动速度
    NavMeshAgent agent;

    [Header("目的地设置")]
    public float arrivalDistance = 2f;         // 接近目的地的距离阈值，小于该值视为到达

    [Header("动画设置")]
    private Animator anim;                      // Animator 组件
    private AnimationController animController; // 动画控制器

    [Header("战斗设置")]
    public float detectionRadius = 8f;          // 敌人检测半径
    public float attackRange = 2f;              // 攻击范围
    public float attackCooldown = 1.5f;         // 攻击冷却时间
    public int attackPower = 25;                // 攻击力
    private float lastAttackTime = 0f;          // 上次攻击时间
    private Transform enemyTransform;           // 当前目标敌人
    private float checkEnemyInterval = 0.5f;    // 检查敌人的时间间隔

    // 命令信息存储
    private Dictionary<string, string> recallMessage = new Dictionary<string, string>
    {
        {"谁", "徐晃"},
        {"带多少兵", "0,0,0"}, // 设置为0表示没有兵力
        {"去什么地方", ""}, // 初始不设置目的地
        {"以什么策略", "方阵"},
        {"干什么事", "Defend"}
    };

    // 命令队列实现
    public Stack<Dictionary<string, string>> stackPrivate = new Stack<Dictionary<string, string>>();

    // 状态机定义
    private enum State { Idle, Attack, Defend, Withdraw, Dying };
    private State currentState = State.Idle;
    [Header("状态机状态")]
    public string currentStateString = "空闲"; // 用于在Inspector中显示当前状态

    // 状态机和路径检查的协程
    private Coroutine stateMachineCoroutine;
    private Coroutine pathCheckCoroutine;

    [Header("调试信息")]
    public string lastDecisionJson; // 最后一次决策的JSON内容
    public string lastDecisionTime; // 最后一次决策的时间
    public bool debugMode = true;

    // 动画控制器类
    public class AnimationController
    {
        private Animator animator;
        private static readonly int MoveX = Animator.StringToHash("MoveX");
        private static readonly int MoveY = Animator.StringToHash("MoveY");
        private static readonly int IsAttacking = Animator.StringToHash("Attack");
        private static readonly int IsDead = Animator.StringToHash("Dead");
        private static readonly int IsMoving = Animator.StringToHash("IsMoving");

        public AnimationController(Animator animator)
        {
            this.animator = animator;
        }

        public void SetMovement(Vector2 movement)
        {
            if (animator == null) return;

            animator.SetFloat(MoveX, movement.x);
            animator.SetFloat(MoveY, movement.y);
            animator.SetBool(IsMoving, movement.magnitude > 0.1f);
        }

        public void TriggerAttack(bool isAttacking)
        {
            if (animator == null) return;

            animator.SetBool(IsAttacking, isAttacking);
        }

        public void TriggerDeath()
        {
            if (animator == null) return;

            animator.SetTrigger(IsDead);
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        // 初始化观察变量
        formation = "方阵";
        currentPosition = transform.position.ToString();

        // 初始化状态机
        currentState = State.Idle;

        stackPrivate.Push(new Dictionary<string, string>(recallMessage));

        // 初始化NavMeshAgent
        agent = GetComponent<NavMeshAgent>();
        if (agent != null)
        {
            agent.updateRotation = false;
            agent.updateUpAxis = false;
            agent.speed = speed;
            agent.stoppingDistance = attackRange * 0.8f;
            Debug.Log($"【徐晃】NavMeshAgent已初始化，速度设为:{agent.speed}");
        }
        else
        {
            Debug.LogError("【徐晃】未找到NavMeshAgent组件");
        }

        // 初始化Animator
        anim = GetComponent<Animator>();
        animController = new AnimationController(anim);

        // 启动状态机协程
        stateMachineCoroutine = StartCoroutine(StateMachine());

        // 启动路径检查协程
        pathCheckCoroutine = StartCoroutine(CheckPathRoutine());

        // 启动敌人检测协程
        StartCoroutine(DetectEnemies());

        Debug.Log("【徐晃】初始化完成，等待命令");
    }

    // Update is called once per frame
    void Update()
    {
        // 更新当前位置
        currentPosition = transform.position.ToString("F1");

        // 检查生命值，如果小于等于0且不在死亡状态，则触发死亡
        if (health <= 0 && currentState != State.Dying)
        {
            Debug.Log($"<color=red>【徐晃】Update检测到生命值为{health}，小于等于0，触发死亡</color>");
            health = 0;
            Die();
        }

        // 更新状态机字符串显示（用于观察）
        switch (currentState)
        {
            case State.Idle:
                currentStateString = "空闲";
                break;
            case State.Attack:
                currentStateString = "进攻";
                break;
            case State.Defend:
                currentStateString = "防守";
                break;
            case State.Withdraw:
                currentStateString = "撤退";
                break;
            case State.Dying:
                currentStateString = "阵亡";
                break;
        }
    }

    // 状态机协程
    private IEnumerator StateMachine()
    {
        while (true)
        {
            // 更新状态机字符串显示（用于观察）
            switch (currentState)
            {
                case State.Idle:
                    currentStateString = "空闲";
                    yield return IdleState();
                    break;

                case State.Attack:
                    currentStateString = "进攻";
                    yield return AttackState();
                    break;

                case State.Defend:
                    currentStateString = "防守";
                    yield return DefendState();
                    break;

                case State.Withdraw:
                    currentStateString = "撤退";
                    yield return WithdrawState();
                    break;

                case State.Dying:
                    currentStateString = "阵亡";
                    // 死亡状态已由Die()方法单独处理，不在这里执行
                    // 这样可以确保死亡动画不会被状态机中断
                    yield return new WaitForSeconds(0.5f);
                    break;
            }

            yield return null;  // 确保每个状态之间有一次休息
        }
    }

    // 路径检查协程
    private IEnumerator CheckPathRoutine()
    {
        while (true)
        {
            // 检查导航状态
            if (agent != null && agent.isActiveAndEnabled && !agent.isStopped)
            {
                // 更新当前位置
                currentPosition = transform.position.ToString("F1");

                // 检查目标是否存在
                if (!string.IsNullOrEmpty(targetPosition) && targetPosition != "当前位置")
                {
                    GameObject targetObj = GameObject.Find(targetPosition);
                    if (targetObj != null)
                    {
                        float distanceToTarget = Vector3.Distance(transform.position, targetObj.transform.position);
                        // 如果已接近目标
                        if (distanceToTarget <= arrivalDistance)
                        {
                            if (!is_arrive)
                            {
                                Debug.Log($"【徐晃】已到达目标位置: {targetPosition}，距离: {distanceToTarget:F2}");
                                is_arrive = true;

                                // 停止导航
                                agent.isStopped = true;
                                agent.velocity = Vector3.zero;
                            }
                        }
                    }
                }
            }

            yield return new WaitForSeconds(0.5f);
        }
    }

    // 空闲状态处理
    private IEnumerator IdleState()
    {
        if (stackPrivate.Count > 0)
        {
            Debug.Log("【徐晃】处理新命令");

            // 获取栈顶命令
            Dictionary<string, string> newCommand = stackPrivate.Pop();

            // 解析命令内容
            string destination = newCommand.ContainsKey("去什么地方") ? newCommand["去什么地方"] : "当前位置";
            string action = newCommand.ContainsKey("干什么事") ? newCommand["干什么事"] : "Defend";
            string troopsConfig = newCommand.ContainsKey("带多少兵") ? newCommand["带多少兵"] : "0,0,0";

            // 更新目标位置和状态
            targetPosition = destination;
            if (!string.IsNullOrEmpty(destination) && destination != "当前位置")
            {
                UpdateDestination(destination);
            }

            // 更新阵型
            formation = newCommand.ContainsKey("以什么策略") ? newCommand["以什么策略"] : "方阵";

            // 更新活动状态
            activity = MapActionToActivity(action);

            // 更新兵力配置
            string[] troops = troopsConfig.Split(',');
            if (troops.Length >= 3)
            {
                int.TryParse(troops[0], out cavalryAccount);
                int.TryParse(troops[1], out archerAccount);
                int.TryParse(troops[2], out infantryAccount);
            }

            // 根据命令更新状态
            switch (action)
            {
                case "Attack":
                    currentState = State.Attack;
                    break;
                case "Defend":
                    currentState = State.Defend;
                    break;
                case "Withdraw":
                    currentState = State.Withdraw;
                    break;
                default:
                    Debug.LogWarning($"【徐晃】未知指令: {action}，默认使用防守状态");
                    currentState = State.Defend;
                    break;
            }

            // 确保在状态改变时立即更新导航
            if (!string.IsNullOrEmpty(destination) && destination != "当前位置")
            {
                GameObject destObj = GameObject.Find(destination);
                if (destObj != null && agent != null && agent.isActiveAndEnabled)
                {
                    agent.isStopped = false;
                    Debug.Log($"【徐晃】设置为可移动状态，目标: {destination}");
                }
            }

            Debug.Log($"【徐晃】命令已处理: 动作={action}, 目标={destination}, 阵型={formation}, 兵力={troopsConfig}");

            yield return new WaitForSeconds(0.5f);
        }
        else
        {
            // 没有命令时，保持空闲状态
            yield return new WaitForSeconds(1f);
        }
    }

    // 进攻状态处理
    private IEnumerator AttackState()
    {
        if(enemyTransform != null)
        {
            Debug.Log($"【徐晃】进入攻击状态，目标: {enemyTransform?.name}");
        }
        
        // 设置攻击相关参数
        if (agent != null && agent.isActiveAndEnabled)
        {
            agent.stoppingDistance = attackRange * 0.8f;
        }
        is_attacking = true;
        
        // 主攻击循环
        while (true)
        {
            // 1. 检查敌人是否有效
            if (enemyTransform == null || !enemyTransform.gameObject.activeInHierarchy)
            {
                Debug.Log($"【徐晃】目标敌人不存在或已被击败，停止攻击状态");
                // 重置状态
                is_attacking = false;
                if (animController != null)
                {
                    animController.TriggerAttack(false);
                }
                // 切换回空闲状态
                currentState = State.Idle;
                yield break;
            }
            
            // 2. 检查距离
            float distanceToEnemy = Vector3.Distance(transform.position, enemyTransform.position);
            
            // 如果敌人超出检测范围，放弃追击
            if (distanceToEnemy > detectionRadius * 1.2f)
            {
                Debug.Log($"【徐晃】敌人已超出攻击范围，放弃追击");
                is_attacking = false;
                enemyTransform = null;
                if (animController != null)
                {
                    animController.TriggerAttack(false);
                }
                currentState = State.Idle;
                yield break;
            }
            
            // 3. 处理移动或攻击
            if (agent != null && agent.isActiveAndEnabled)
            {
                // 如果在攻击范围内
                if (distanceToEnemy <= attackRange)
                {
                    // 停止移动并面向敌人
                    agent.isStopped = true;
                    agent.velocity = Vector3.zero;
                    FaceTarget(enemyTransform.position);
                    
                    // 如果攻击冷却结束，执行攻击
                    if (Time.time >= lastAttackTime + attackCooldown)
                    {
                        Debug.Log($"【徐晃】攻击敌人: {enemyTransform.name}，距离: {distanceToEnemy:F2}");
                        
                        // 再次检查敌人是否有效（可能在移动过程中被击败）
                        if (enemyTransform == null || !enemyTransform.gameObject.activeInHierarchy)
                        {
                            Debug.Log($"【徐晃】准备攻击时发现敌人已被击败，停止攻击");
                            is_attacking = false;
                            enemyTransform = null;
                            if (animController != null)
                            {
                                animController.TriggerAttack(false);
                            }
                            currentState = State.Idle;
                            yield break;
                        }
                        
                        // 执行攻击
                        if (animController != null)
                        {
                            animController.TriggerAttack(true);
                        }
                        PerformAttack();
                        lastAttackTime = Time.time;
                        
                        // 等待攻击动画播放
                        yield return new WaitForSeconds(attackCooldown * 0.5f);
                        
                        // 重置攻击动画
                        if (animController != null)
                        {
                            animController.TriggerAttack(false);
                        }
                        
                        // 攻击后短暂等待
                        yield return new WaitForSeconds(0.2f);
                    }
                }
                else
                {
                    // 如果不在攻击范围内，移动接近敌人
                    agent.isStopped = false;
                    agent.SetDestination(enemyTransform.position);
                    
                    // 更新移动动画
                    UpdateMovementAnimation();
                    
                    // 移动过程中的短暂等待
                    yield return new WaitForSeconds(0.1f);
                }
            }
            
            // 短暂等待，避免每帧都执行
            yield return new WaitForSeconds(0.1f);
        }
    }

    // 防守状态处理
    private IEnumerator DefendState()
    {
        // 防守状态下，到达目标位置后停止移动
        if (!string.IsNullOrEmpty(targetPosition) && targetPosition != "当前位置")
        {
            GameObject targetObj = GameObject.Find(targetPosition);
            if (targetObj != null && agent != null && agent.isActiveAndEnabled)
            {
                // 确保导航是激活的
                if (agent.isStopped)
                {
                    agent.isStopped = false;
                }

                // 更新目标位置
                agent.SetDestination(targetObj.transform.position);
            }
        }

        yield return new WaitForSeconds(1f);
    }

    // 撤退状态处理
    private IEnumerator WithdrawState()
    {
        // 撤退状态下，快速向目标移动
        if (!string.IsNullOrEmpty(targetPosition) && targetPosition != "当前位置")
        {
            GameObject targetObj = GameObject.Find(targetPosition);
            if (targetObj != null && agent != null && agent.isActiveAndEnabled)
            {
                // 确保导航是激活的
                if (agent.isStopped)
                {
                    agent.isStopped = false;
                }

                // 更新目标位置
                agent.SetDestination(targetObj.transform.position);
            }
        }

        yield return new WaitForSeconds(1f);
    }

    // 接收决策信息
    public void ReceiveDecision(Wei_GeneralDecision decision)
    {
        // 记录决策信息
        lastDecisionJson = JsonUtility.ToJson(decision);
        lastDecisionTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

        // 创建命令字典
        Dictionary<string, string> command = new Dictionary<string, string>
        {
            {"谁", generalName},
            {"带多少兵", decision.士兵数量},
            {"去什么地方", decision.目的地},
            {"以什么策略", decision.阵型},
            {"干什么事", MapActionToCommand(decision.行为)}
        };

        // 将命令添加到栈中
        stackPrivate.Push(command);

        Debug.Log($"【徐晃】收到新命令: {JsonUtility.ToJson(command)}");
    }

    // 将AI行为映射到命令
    private string MapActionToCommand(string aiAction)
    {
        switch (aiAction.ToLower())
        {
            case "进攻":
                return "Attack";
            case "防守":
                return "Defend";
            case "撤退":
                return "Withdraw";
            case "支援":
                return "Support";
            default:
                return "Defend"; // 默认为防守
        }
    }

    // 将命令映射到活动状态
    private string MapActionToActivity(string command)
    {
        switch (command.ToLower())
        {
            case "attack":
                return "进攻";
            case "defend":
                return "防守";
            case "withdraw":
                return "撤退";
            case "support":
                return "支援";
            default:
                return "防守"; // 默认为防守
        }
    }

    // 更新目标位置
    private void UpdateDestination(string destination)
    {
        if (string.IsNullOrEmpty(destination) || destination == "当前位置")
        {
            Debug.Log("【徐晃】目标位置无效，保持当前位置");
            return;
        }

        GameObject targetObj = GameObject.Find(destination);
        if (targetObj != null)
        {
            if (agent != null && agent.isActiveAndEnabled)
            {
                agent.SetDestination(targetObj.transform.position);
                Debug.Log($"【徐晃】设置新目标: {destination}, 位置: {targetObj.transform.position}");
            }
            else
            {
                Debug.LogError("【徐晃】NavMeshAgent不可用，无法设置目标");
            }
        }
        else
        {
            Debug.LogError($"【徐晃】找不到目标对象: {destination}");
        }
    }

    // 检查是否接近目标
    private bool CheckIfNearDestination()
    {
        if (string.IsNullOrEmpty(targetPosition) || targetPosition == "当前位置")
        {
            return true; // 如果没有目标，认为已经到达
        }

        GameObject targetObj = GameObject.Find(targetPosition);
        if (targetObj != null)
        {
            float distance = Vector3.Distance(transform.position, targetObj.transform.position);
            return distance <= arrivalDistance;
        }

        return false;
    }

    // 测试移动方法
    public void TestMove(string destination)
    {
        Debug.Log($"【徐晃】测试移动到: {destination}");
        UpdateDestination(destination);
    }

    // 清除所有命令
    public void ClearAllCommands()
    {
        stackPrivate.Clear();
        Debug.Log("【徐晃】已清除所有命令");
    }

    // 检测敌人协程
    private IEnumerator DetectEnemies()
    {
        while (true)
        {
            // 检查当前目标是否已经无效（被击败或禁用）
            if (enemyTransform != null && !enemyTransform.gameObject.activeInHierarchy)
            {
                Debug.Log($"【徐晃】检测到当前目标敌人已被击败或不存在，重置目标");
                enemyTransform = null;
                is_attacking = false;
                
                // 重置攻击动画
                if (animController != null)
                {
                    animController.TriggerAttack(false);
                }
                
                // 如果当前状态是攻击状态，切换回空闲状态
                if (currentState == State.Attack)
                {
                    currentState = State.Idle;
                }
            }
            
            // 只有当不在攻击状态或者没有当前目标时才寻找新敌人
            if (currentState != State.Attack || enemyTransform == null)
            {
                Transform newEnemy = FindNearestEnemy();
                
                // 确保新找到的敌人是有效的且处于激活状态
                if (newEnemy != null && newEnemy.gameObject.activeInHierarchy)
                {
                    enemyTransform = newEnemy;
                    Debug.Log($"【徐晃】发现敌人: {enemyTransform.name}，准备攻击!");
                    currentState = State.Attack;
                    is_attacking = true;
                }
            }

            yield return new WaitForSeconds(checkEnemyInterval);
        }
    }

    // 寻找最近的敌人
    private Transform FindNearestEnemy()
    {
        // 获取检测范围内的所有碰撞体
        Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, detectionRadius);

        Transform closestEnemy = null;
        float closestDistance = detectionRadius;

        foreach (Collider2D collider in colliders)
        {
            // 忽略自己
            if (collider.gameObject == gameObject)
                continue;

            GameObject potentialEnemy = collider.gameObject;
            string enemyCountry = GetObjectCountry(potentialEnemy);

            // 如果有国家且不是己方国家，则视为敌人
            if (!string.IsNullOrEmpty(enemyCountry) && enemyCountry != country)
            {
                float distance = Vector2.Distance(transform.position, potentialEnemy.transform.position);
                if (distance < closestDistance)
                {
                    closestDistance = distance;
                    closestEnemy = potentialEnemy.transform;
                }
            }
        }

        return closestEnemy;
    }

    // 获取对象的国家
    private string GetObjectCountry(GameObject obj)
    {
        if (obj == null) return null;

        // 从标签判断是否是将军
        string tag = obj.tag;
        if (!string.IsNullOrEmpty(tag) && tag.Contains("_General"))
        {
            // 从标签获取国家信息
            if (tag.StartsWith("Wu_")) return "Wu";
            if (tag.StartsWith("Shu_")) return "Shu";
            if (tag.StartsWith("Wei_")) return "Wei";
        }

        // 判断是否是士兵
        ShiBing enemyShiBing = obj.GetComponent<ShiBing>();
        if (enemyShiBing != null && !string.IsNullOrEmpty(enemyShiBing.country))
        {
            return enemyShiBing.country;
        }

        // 判断其他具有country字段的对象
        MonoBehaviour[] components = obj.GetComponents<MonoBehaviour>();
        if (components != null)
        {
            foreach (MonoBehaviour comp in components)
            {
                if (comp == null) continue;

                try
                {
                    System.Reflection.FieldInfo field = comp.GetType().GetField("country");
                    if (field != null)
                    {
                        string country = (string)field.GetValue(comp);
                        if (!string.IsNullOrEmpty(country))
                        {
                            return country;
                        }
                    }
                }
                catch (System.Exception e)
                {
                    Debug.LogWarning($"获取国家属性时出错: {e.Message}");
                }
            }
        }

        return null;
    }

    // 执行攻击
    private void PerformAttack()
    {
        if (enemyTransform == null || !enemyTransform.gameObject.activeInHierarchy) return;

        Debug.Log($"【徐晃】攻击 {enemyTransform.name}");

        // 对敌人造成伤害
        DealDamageToEnemy();
    }

    // 对敌人造成伤害
    private void DealDamageToEnemy()
    {
        if (enemyTransform == null) return;

        // 计算实际伤害值（可以添加随机浮动）
        int actualDamage = CalculateDamage();

        // 尝试对敌人造成伤害
        bool damageDealt = false;

        // 检查敌人是否是士兵
        ShiBing enemyShiBing = enemyTransform.GetComponent<ShiBing>();
        if (enemyShiBing != null)
        {
            enemyShiBing.TakeDamage(actualDamage);
            damageDealt = true;
        }

        // 检查敌人是否有实现了TakeDamage方法的组件
        if (!damageDealt)
        {
            try
            {
                var methodInfo = enemyTransform.GetType().GetMethod("TakeDamage");
                if (methodInfo != null)
                {
                    methodInfo.Invoke(enemyTransform, new object[] { actualDamage });
                    damageDealt = true;
                }
            }
            catch (System.Exception e)
            {
                Debug.LogWarning($"尝试调用TakeDamage方法时出错: {e.Message}");
            }
        }
    }

    // 计算实际伤害
    private int CalculateDamage()
    {
        // 基础伤害
        float baseDamage = attackPower;

        // 随机浮动 (±20%)
        float randomFactor = UnityEngine.Random.Range(0.8f, 1.2f);

        // 暴击判定 (15%几率)
        bool isCritical = UnityEngine.Random.value < 0.15f;
        float criticalMultiplier = isCritical ? 1.5f : 1.0f;

        // 计算最终伤害
        int finalDamage = Mathf.RoundToInt(baseDamage * randomFactor * criticalMultiplier);

        // 输出伤害日志
        if (isCritical)
        {
            Debug.Log($"【徐晃】对 {enemyTransform.name} 造成了 <color=red>暴击</color> {finalDamage} 点伤害!");
        }
        else
        {
            Debug.Log($"【徐晃】对 {enemyTransform.name} 造成了 {finalDamage} 点伤害");
        }

        return finalDamage;
    }

    // 受到伤害
    public void TakeDamage(int damage)
    {
        // 如果已经死亡，不再处理伤害
        if (health <= 0 || currentState == State.Dying) return;

        // 应用伤害
        health -= damage;

        // 显示伤害日志
        Debug.Log($"【徐晃】受到 {damage} 点伤害，剩余生命值: {health}");

        // 播放受伤动画/音效
        PlayHitFeedback();

        // 检查是否死亡
        if (health <= 0)
        {
            health = 0;  // 确保生命值不为负
            Debug.Log($"<color=red>【徐晃】生命值为0，触发死亡</color>");
            Die();
        }
    }

    // 播放受伤反馈
    private void PlayHitFeedback()
    {
        // 在此处可以添加受伤时的视觉/音效反馈
        StartCoroutine(FlashSprite());
    }

    // 精灵闪烁效果
    private IEnumerator FlashSprite()
    {
        SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
        if (spriteRenderer == null) yield break;

        // 保存原始颜色
        Color originalColor = spriteRenderer.color;

        // 闪烁为红色
        spriteRenderer.color = Color.red;

        // 等待短暂时间
        yield return new WaitForSeconds(0.1f);

        // 恢复原始颜色
        spriteRenderer.color = originalColor;
    }

    // 死亡处理
    private void Die()
    {
        Debug.Log($"<color=red>【徐晃】已阵亡</color>");

        // 切换到死亡状态
        currentState = State.Dying;

        // 确保状态机立即处理死亡状态
        StartCoroutine(DyingState());
    }

    // 死亡状态处理
    private IEnumerator DyingState()
    {
        Debug.Log($"<color=red>【徐晃】进入死亡状态</color>");

        // 停止所有协程但保留当前协程
        if (stateMachineCoroutine != null) StopCoroutine(stateMachineCoroutine);
        if (pathCheckCoroutine != null) StopCoroutine(pathCheckCoroutine);

        // 停止所有移动
        if (agent != null && agent.isActiveAndEnabled)
        {
            agent.isStopped = true;
            agent.velocity = Vector3.zero;
            // 安全地禁用NavMeshAgent
            agent.enabled = false;
        }

        // 禁用检测敌人
        enemyTransform = null;
        is_attacking = false;

        // 禁用碰撞体
        Collider2D col = GetComponent<Collider2D>();
        if (col != null)
        {
            col.enabled = false;
        }

        // 播放死亡动画
        if (anim != null)
        {
            // 使用"Dead"触发器参数触发死亡动画
            anim.SetTrigger("Dead");

            // 可选：确保停止其他动画状态
            anim.SetBool("isAttacking", false);
            anim.SetFloat("MoveX", 0);
            anim.SetFloat("MoveY", 0);
        }

        // 生成死亡特效（如果有的话）
        PlayDeathEffect();

        // 等待动画播放完成
        yield return WaitForDeathAnimationToFinish();

        // 动画播放完成后销毁对象
        Debug.Log($"<color=red>【徐晃】死亡动画播放完成，即将被销毁</color>");
        Destroy(gameObject);
    }

    // 等待死亡动画播放完成
    private IEnumerator WaitForDeathAnimationToFinish()
    {
        // 等待一小段时间确保动画开始播放
        yield return new WaitForSeconds(0.1f);

        // 获取当前动画状态信息
        AnimatorStateInfo stateInfo;
        float animationLength = 1.0f; // 死亡动画的大概长度，根据实际情况调整
        float timer = 0f;

        // 等待动画完全播放完毕
        while (timer < animationLength)
        {
            stateInfo = anim.GetCurrentAnimatorStateInfo(0);

            // 检查是否正在播放Dead动画
            if (stateInfo.IsName("Dead"))
            {
                timer += Time.deltaTime;

                // 输出当前播放进度，便于调试
                if (timer % 0.2f < 0.01f && debugMode)
                {
                    Debug.Log($"【徐晃】死亡动画播放进度: {timer}/{animationLength}秒");
                }
            }
            else
            {
                // 如果不是Dead状态，可能是动画系统出现问题，直接跳出
                if (debugMode)
                {
                    Debug.LogWarning($"【徐晃】不在Dead动画状态，当前状态: {stateInfo.fullPathHash}");
                }
                break;
            }

            yield return null;
        }

        // 添加额外的短暂延迟，确保动画完全结束
        yield return new WaitForSeconds(0.2f);

        // 动画已播放完成
        Debug.Log($"【徐晃】死亡动画播放完成");
    }

    // 播放死亡特效
    private void PlayDeathEffect()
    {
        // 播放粒子效果（如果有）
        ParticleSystem particleSystem = GetComponentInChildren<ParticleSystem>();
        if (particleSystem != null)
        {
            particleSystem.Play();
        }

        // 播放音效（如果有）
        AudioSource audioSource = GetComponent<AudioSource>();
        if (audioSource != null)
        {
            // 假设有一个死亡音效剪辑
            AudioClip deathSound = Resources.Load<AudioClip>("Sounds/GeneralDeath");
            if (deathSound != null)
            {
                audioSource.clip = deathSound;
                audioSource.Play();
            }
        }
    }

    // 更新移动动画
    private void UpdateMovementAnimation()
    {
        if (animController == null) return;

        // 根据agent速度更新动画
        Vector2 velocity = new Vector2(agent.velocity.x, agent.velocity.y);
        if (velocity.magnitude > 0.1f)
        {
            animController.SetMovement(velocity.normalized);
        }
        else
        {
            animController.SetMovement(Vector2.zero);
        }
    }

    // 面向目标
    private void FaceTarget(Vector3 targetPosition)
    {
        Vector3 direction = (targetPosition - transform.position).normalized;
        Vector2 facingDirection = new Vector2(direction.x, direction.y).normalized;

        if (animController != null)
        {
            animController.SetMovement(facingDirection);
        }
    }
}
